<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'"
        />
        <div class="options">
          <el-button
            :loading="btnLoading"
            type="primary"
            @click="dataFormSave()"
            v-if="!isDetail"
          >
            保 存
          </el-button>
          <el-button
            type="success"
            :loading="btnLoading"
            @click="dataFormSubmit()"
            v-if="!isDetail"
          >
            发 布
          </el-button>
          <el-button @click="goBack"> 取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '1200px' }"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-width="150px"
        >
          <template v-if="!loading">
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="基本信息">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考试名称" prop="fullName">
                <el-input
                  v-model="dataForm.fullName"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="试卷名称" prop="examPaperId">
                <popupSelect
                  v-model="dataForm.examPaperId"
                  customUrlPostType="POST"
                  data-type="customUrl"
                  interfaceUrl="api/exam/paper/Selector"
                  placeholder="请选择"
                  clearable
                  field="examPaperId"
                  interfaceId="api/exam/paper/Select/"
                  :columnOptions="examPaperIdcolumnOptions"
                  propsValue="id"
                  relationField="fullName"
                  popupType="dialog"
                  popupTitle="选择数据"
                  popupWidth="800px"
                  hasPage
                  :pageSize="20"
                >
                </popupSelect>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考试目录" prop="categoryId">
                <TreeSelect
                  v-model="dataForm.categoryId"
                  placeholder="请选择"
                  :isChangeFather="false"
                  clearable
                  :options="categoryIdOptions"
                  :props="categoryIdProps"
                >
                </TreeSelect>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="考试时间" prop="startDatetimeTemp">
                <el-date-picker
                  v-model="dataForm.startDatetimeTemp"
                  type="datetimerange"
                  value-format="timestamp"
                  format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  :default-time="['08:00:00', '24:00:00']"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考试时长" prop="examLength">
                <el-input-number
                  v-model="dataForm.examLength"
                  placeholder="数字文本"
                  :max="120"
                  :step="1"
                  controls-position="right"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="及格线" prop="passLine">
                <el-input-number
                  v-model="dataForm.passLine"
                  placeholder="数字文本"
                  :min="1"
                  :max="100"
                  :step="1"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="考试介绍" prop="description">
                <el-input
                  v-model="dataForm.description"
                  placeholder="请输入"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="24">-->
            <!--              <el-form-item label-width="0">-->
            <!--                <groupTitle content-position="left" content="学习证书设置">-->
            <!--                </groupTitle>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="证书模板" prop="certificateId">-->
            <!--                <popupSelect-->
            <!--                  v-model="dataForm.certificateId"-->
            <!--                  placeholder="请选择"-->
            <!--                  clearable-->
            <!--                  field="certificateId"-->
            <!--                  interfaceId=""-->
            <!--                  :columnOptions="certificateIdcolumnOptions"-->
            <!--                  propsValue="id"-->
            <!--                  relationField="fullName"-->
            <!--                  popupType="dialog"-->
            <!--                  popupTitle="选择数据"-->
            <!--                  popupWidth="800px"-->
            <!--                >-->
            <!--                </popupSelect>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="防作弊">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="试题随机打乱"
                prop="preventionQuestionRandomizes"
              >
                <el-switch
                  v-model="dataForm.preventionQuestionRandomizes"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="选项随机打乱"
                prop="preventionItemRandomizes"
              >
                <el-switch
                  v-model="dataForm.preventionItemRandomizes"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="切屏" prop="preventionToggleScreen">
                <el-input-number
                  v-model="dataForm.preventionToggleScreen"
                  placeholder="数字文本"
                  :max="120"
                  :step="1"
                  controls-position="right"
                >
                </el-input-number>
                次后自动交卷
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="切屏" prop="preventionToggleScreenSecond">
                <el-input-number
                  v-model="dataForm.preventionToggleScreenSecond"
                  placeholder="数字文本"
                  :max="120"
                  :step="1"
                  controls-position="right"
                >
                </el-input-number>
                秒后自动交卷
              </el-form-item>
            </el-col>
            <!--            <el-col :span="24">-->
            <!--              <el-form-item label="人脸识别" prop="preventionFace">-->
            <!--                <el-switch-->
            <!--                  v-model="dataForm.preventionFace"-->
            <!--                  :active-value="1"-->
            <!--                  :inactive-value="0"-->
            <!--                >-->
            <!--                </el-switch>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <!--            <el-col :span="24">-->
            <!--              <el-form-item label="ip限制" prop="preventionIp">-->
            <!--                <el-switch-->
            <!--                  v-model="dataForm.preventionIp"-->
            <!--                  :active-value="1"-->
            <!--                  :inactive-value="0"-->
            <!--                >-->
            <!--                </el-switch>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <!--            <el-col :span="24">-->
            <!--              <el-form-item label="考试地址限制" prop="preventionAddr">-->
            <!--                <el-switch-->
            <!--                  v-model="dataForm.preventionAddr"-->
            <!--                  :active-value="1"-->
            <!--                  :inactive-value="0"-->
            <!--                >-->
            <!--                </el-switch>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="考试设置">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="重复考试" prop="examRepeat">
                <el-switch
                  v-model="dataForm.examRepeat"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dataForm.examRepeat">
              <el-form-item label="考试次数设置" prop="examRepeatType">
                <el-radio-group v-model="dataForm.examRepeatType" size="small">
                  <el-radio
                    v-for="(item, index) in examRepeatTypeOptions"
                    :key="index"
                    :label="item.id"
                    :disabled="item.disabled"
                  >
                    {{ item.fullName }}
                  </el-radio>
                </el-radio-group>
                <el-input-number
                  v-if="dataForm.examRepeatType == 'custom'"
                  v-model="dataForm.examRepeatNum"
                  placeholder="数字文本"
                  :step="1"
                  controls-position="right"
                >
                </el-input-number>
                <ComText
                  :style="{ display: 'inline-block' }"
                  :textStyle="{
                    cursor: 'pointer',
                    color: '#8C8C8C',
                    'font-weight': 'normal',
                    'text-decoration': 'none',
                    'font-size': 12,
                    'line-height': 28,
                    'font-style': 'normal',
                    'text-align': 'left',
                    'margin-left': '20px',
                  }"
                  value="考试三次仍未通过后，需进行补考，取补考成绩最好高的10次的成绩的平均分"
                >
                </ComText>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="答案解析设置" prop="examAnswers">
                <el-radio-group v-model="dataForm.examAnswers" size="small">
                  <el-radio
                    v-for="(item, index) in examAnswersOptions"
                    :key="index"
                    :label="item.id"
                    :disabled="item.disabled"
                  >
                    {{ item.fullName }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="开卷考试" prop="examOpen">
                <el-switch
                  v-model="dataForm.examOpen"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="24">-->
            <!--              <el-form-item label="考试签名" prop="examSign">-->
            <!--                <el-switch-->
            <!--                  v-model="dataForm.examSign"-->
            <!--                  :active-value="1"-->
            <!--                  :inactive-value="0"-->
            <!--                >-->
            <!--                </el-switch>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label="通过后允许参加考试" prop="examPass">
                <el-switch
                  v-model="dataForm.examPass"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="评分方式">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填空题评分" prop="examCompletionGrading">
                <el-switch
                  v-model="dataForm.examCompletionGrading"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="问答题评分" prop="examEssayGrading">-->
            <!--                <el-switch-->
            <!--                  v-model="dataForm.examEssayGrading"-->
            <!--                  :active-value="1"-->
            <!--                  :inactive-value="0"-->
            <!--                >-->
            <!--                </el-switch>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="学习奖励">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="学时" prop="learningPeriod">
                <el-input-number
                  v-model="dataForm.learningPeriod"
                  placeholder="数字文本"
                  :step="1"
                  :precision="0"
                  :min="0"
                  controls-position="right"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="学分" prop="learningCredit">
                <el-input-number
                  v-model="dataForm.learningCredit"
                  placeholder="数字文本"
                  :step="1"
                  :precision="0"
                  :min="0"
                  controls-position="right"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="积分" prop="learningIntegral">
                <el-input-number
                  v-model="dataForm.learningIntegral"
                  placeholder="数字文本"
                  :step="1"
                  controls-position="right"
                  :min="0"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="可见范围">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可见范围" prop="scopeType">
                <el-radio-group v-model="dataForm.scopeType" size="small">
                  <el-radio
                    v-for="(item, index) in examScopeOptions"
                    :key="index"
                    :label="item.id"
                    :disabled="item.disabled"
                  >
                    {{ item.fullName }}
                  </el-radio>
                </el-radio-group>
                <FilterSelect
                  v-if="dataForm.scopeType == 'select'"
                  width="500px"
                  v-model="dataForm.scope"
                ></FilterSelect>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <groupTitle content-position="left" content="设置阅卷人">
                </groupTitle>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="阅卷人" prop="examinerUserIds">
                <user-select
                  v-model="dataForm.examinerUserIds"
                  placeholder="请选择"
                  clearable
                  multiple
                >
                </user-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态" prop="enabledMark">
                <el-select
                  v-model="dataForm.enabledMark"
                  placeholder="请选择"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in enabledMarkOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
        </el-form>
      </el-row>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/exam/api/manager";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import FilterSelect from "@/components/Generator/components/filterSelect/index";
import { getCategorySelector } from "@/views/exam/api/category";

export default {
  components: { FilterSelect },
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      isDetail: false,
      btnLoading: false,
      dataForm: {
        fullName: "",
        examPaperId: "",
        categoryId: "",
        startDatetime: undefined,
        endDatetime: undefined,
        startDatetimeTemp: [],
        examLength: 30,
        passLine: 60,
        description: "",
        certificateId: "",
        preventionQuestionRandomizes: 0,
        preventionItemRandomizes: 0,
        preventionToggleScreen: undefined,
        preventionToggleScreenSecond: undefined,
        preventionFace: 0,
        preventionIp: 0,
        preventionAddr: 0,
        examRepeat: 0,
        examRepeatType: "before",
        examRepeatNum: 1,
        examAnswers: "submitAfter",
        examOpen: 0,
        examSign: 0,
        examPass: 0,
        examCompletionGrading: 0,
        examEssayGrading: 0,
        learningPeriod: 1,
        learningCredit: 1,
        learningIntegral: 1,
        scopeType: "all",
        scope: [],
        examinerUserIds: "",
        creatorUserId: "",
        creatorTime: "",
        enabledMark: "0",
      },
      rules: {
        fullName: [
          {
            required: true,
            message: "请输入考试名称",
            trigger: "blur",
          },
        ],
        examPaperId: [
          {
            required: true,
            message: "请选择试卷",
            trigger: "change",
          },
        ],
        startDatetimeTemp: [
          {
            required: true,
            message: "请选择限制考试日期区间",
            trigger: "change",
          },
        ],
        examLength: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: ["blur", "change"],
          },
        ],
        passLine: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: ["blur", "change"],
          },
        ],
      },
      examPaperIdcolumnOptions: [
        {
          label: "名称",
          value: "fullName",
        },
        {
          label: "创建人",
          value: "creatorUserId",
        },
        {
          label: "创建时间",
          value: "creatorTime",
        },
      ],
      categoryIdOptions: [],
      categoryIdProps: { children: "children", label: "fullName", value: "id" },
      certificateIdcolumnOptions: [],
      examRepeatTypeOptions: [
        { fullName: "考试结束前无限制重考", id: "before" },
        { fullName: "自定义重考次数", id: "custom" },
      ],
      examAnswersOptions: [
        { fullName: "交卷后", id: "submitAfter" },
        {
          fullName: "及格后",
          id: "passAfter",
        },
        { fullName: "考试结束后", id: "examAfter" },
        { fullName: "不允许查看", id: "notAllow" },
      ],
      examScopeOptions: [
        { fullName: "全公司", id: "all" },
        { fullName: "仅创建人", id: "creator" },
        {
          fullName: "部门/人员",
          id: "select",
        },
      ],
      enabledMarkOptions: [
        { fullName: "草稿", id: "0" },
        { fullName: "发布", id: "1" },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getCategoryOptions();
  },
  mounted() {},
  methods: {
    getCategoryOptions() {
      // 获取所属目录
      getCategorySelector({
        folderType: "exam",
        parentId: "-1",
        menuId: "111",
      }).then((res) => {
        this.categoryIdOptions = res.data;
      });
    },
    goBack() {
      this.$emit("refresh");
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }

      this.dataForm.scope = [];
      this.dataForm.scopeType = "all";
      this.dataForm.examLength = 30;
      this.dataForm.passLine = 60;
      this.dataForm.enabledMark = "0";
      this.dataForm.examAnswers = "submitAfter";
      this.dataForm.examinerUserIds = [this.$store.getters.userInfo.userId];
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.examRepeatType = "before";
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    dataFormSave() {
      var _data = this.dataList();
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.dataForm.enabledMark = 1;
      this.dataFormSave();
    },
    getScopeChangeData(scopeData) {
      this.dataForm.scope = scopeData;
    },
    scopeFormat(data) {
      let scope = {};
      if (data) {
        let organizesArr = [];
        data.forEach((item, index) => {
          if (item.type == "company" || item.type == "department") {
            organizesArr = organizesArr.concat(item.selectArr);
          }
          if (item.type == "Role") {
            scope.scopeRoles = item.selectArr.join(",");
          }
          if (item.type == "Position") {
            scope.scopePositions = item.selectArr.join(",");
          }
          if (item.type == "Group") {
            scope.scopeGroups = item.selectArr.join(",");
          }
          if (item.type == "user") {
            scope.scopeUsers = item.selectArr.join(",");
          }
          if (item.type == "exclude") {
            scope.scopeExcludeUsers = item.selectArr.join(",");
          }
        });
        scope.scopeOrganizes = organizesArr.join(",");
      }
      return scope;
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));

      let scopeFormatProperties = this.scopeFormat(_data.scope);
      _data.preventionQuestionRandomizes = parseInt(
        _data.preventionQuestionRandomizes
      );

      if (_data.startDatetimeTemp) {
        _data.startDatetime = _data.startDatetimeTemp[0];
        _data.endDatetime = _data.startDatetimeTemp[1];
      }
      _data.scope = JSON.stringify(_data.scope);
      _data.scopeOrganizes = scopeFormatProperties.scopeOrganizes;
      _data.scopeGroups = scopeFormatProperties.scopeGroups;
      _data.scopeRoles = scopeFormatProperties.scopeRoles;
      _data.scopePositions = scopeFormatProperties.scopePositions;
      _data.scopeUsers = scopeFormatProperties.scopeUsers;
      _data.scopeExcludeUsers = scopeFormatProperties.scopeExcludeUsers;

      _data.examinerUserIds = JSON.stringify(_data.examinerUserIds);
      _data.preventionItemRandomizes = parseInt(_data.preventionItemRandomizes);
      _data.preventionFace = parseInt(_data.preventionFace);
      _data.preventionIp = parseInt(_data.preventionIp);
      _data.preventionAddr = parseInt(_data.preventionAddr);
      _data.examRepeat = parseInt(_data.examRepeat);
      _data.examOpen = parseInt(_data.examOpen);
      _data.examSign = parseInt(_data.examSign);
      _data.examPass = parseInt(_data.examPass);
      _data.examCompletionGrading = parseInt(_data.examCompletionGrading);
      _data.examEssayGrading = parseInt(_data.examEssayGrading);
      return _data;
    },
    dataInfo(dataAll) {
      console.log("------------dataAll", dataAll);
      let _dataAll = dataAll;
      if (_dataAll.startDatetime && _dataAll.endDatetime) {
        this.$set(_dataAll, "startDatetimeTemp", [
          _dataAll.startDatetime,
          _dataAll.endDatetime,
        ]);
      }
      _dataAll.preventionQuestionRandomizes = parseInt(
        _dataAll.preventionQuestionRandomizes
      );
      _dataAll.preventionItemRandomizes = parseInt(
        _dataAll.preventionItemRandomizes
      );
      _dataAll.scope = JSON.parse(_dataAll.scope);

      _dataAll.examinerUserIds = JSON.parse(_dataAll.examinerUserIds);
      _dataAll.preventionFace = parseInt(_dataAll.preventionFace);
      _dataAll.preventionIp = parseInt(_dataAll.preventionIp);
      _dataAll.preventionAddr = parseInt(_dataAll.preventionAddr);
      _dataAll.examRepeat = parseInt(_dataAll.examRepeat);
      _dataAll.examOpen = parseInt(_dataAll.examOpen);
      _dataAll.examSign = parseInt(_dataAll.examSign);
      _dataAll.examPass = parseInt(_dataAll.examPass);
      _dataAll.examCompletionGrading = parseInt(_dataAll.examCompletionGrading);
      _dataAll.examEssayGrading = parseInt(_dataAll.examEssayGrading);
      console.log("------------_dataAll", _dataAll);
      this.dataForm = _dataAll;
    },
  },
};
</script>
